<template>
  <div class="main">
    <div class="title">
      <div>图书柜管理</div>
      <el-button type="primary" :icon="CirclePlus" @click="addCabinet"
        >新增图书柜</el-button
      >
    </div>
    <div class="search-bar">
      <div class="label-input">
        <span>搜索内容：</span>
        <el-input v-model="query.queryName" style="width: 200px" />
      </div>
      <div class="label-input">
        <span>选择区域：</span>
        <el-select
          v-model="query.areaId"
          placeholder="请选择区域"
          style="width: 200px"
        >
          <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
      <el-button class="search-btn" @click="getTabelData">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>
    <div class="cut-line"></div>
    <el-table
      :data="tabelData"
      height="400"
      style="width: 100%"
      border
      v-loading="loading"
      :header-cell-style="headerStyle"
      :row-class-name="tableRowClassName"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column type="index" align="center" label="#" width="50" />
      <el-table-column
        prop="name"
        align="center"
        label="图书柜名称/柜格名称"
        width="150"
      />
      <el-table-column
        prop="sequenceCode"
        align="center"
        label="序列号"
        width="200"
      />
      <el-table-column
        prop="cameraId"
        align="center"
        label="摄像头ID"
        width="200"
      />
      <el-table-column
        prop="areaName"
        align="center"
        label="区域名称"
        width="200"
      />
      <el-table-column
        prop="code"
        align="center"
        label="柜格编码"
        width="100"
      />
      <el-table-column align="center" label="状态" width="100">
        <template v-slot="scope">
          <div v-if="scope.row.type">{{ scope.row.type }}</div>
          <div v-else>{{ scope.row.isDeleted }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="isOnline"
        align="center"
        label="连接状态"
        width="100"
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        align="center"
        label="创建时间"
        width="200"
      />
      <el-table-column
        align="center"
        label="操作"
        fixed="right"
        min-width="300"
      >
        <template v-slot="scope">
          <div class="table-buts" v-if="scope.row.code">
            <el-button
              style="background-color: #3d839c; color: #fff"
              @click="updateCabinetLat(scope.row)"
              >修改</el-button
            >
            <el-button type="danger" @click="deleteCabinetLat(scope.row.id)"
              >删除</el-button
            >
          </div>
          <div class="table-buts" v-else>
            <el-button
              style="background-color: #3d839c; color: #fff"
              @click="updateCabinet(scope.row)"
              >修改</el-button
            >
            <el-button type="warning" @click="addCabinetLat(scope.row.id)"
              >添加柜格</el-button
            >
            <el-button
              v-if="scope.row.isDeleted == '正常'"
              type="danger"
              @click="endCabinet(scope.row.id)"
              >停用</el-button
            >
            <el-button v-else type="success" @click="startCabinet(scope.row.id)"
              >启用</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="tabelDataTotal"
        :page-size="query.pageSize"
        :current-page="query.pageNum"
        @update:current-page="currentPageChange"
      />
    </div>
    <!-- 添加、修改弹窗 -->
    <el-dialog v-model="dialogTableVisible" :title="title" width="300">
      <div class="dialog-win">
        <el-form
          ref="ruleFormRef"
          :model="table"
          label-width="auto"
          :rules="rules"
        >
          <el-form-item label="图书柜名称：" prop="name">
            <el-input v-model="table.name" style="width: 240px" />
          </el-form-item>
          <el-form-item label="区域地址：" prop="areaId">
            <el-select
              v-model="table.areaId"
              placeholder="请选择区域"
              style="width: 240px"
            >
              <el-option
                v-for="item in areaList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="序列号：" prop="name">
            <el-input v-model="table.sequenceCode" style="width: 240px" />
          </el-form-item>
          <el-form-item label="摄像头ID：" prop="name">
            <el-input v-model="table.cameraId" style="width: 240px" />
          </el-form-item>
          <el-form-item>
            <div class="from-but">
              <el-button type="warning" @click="submit(ruleFormRef)"
                >确定</el-button
              >
              <el-button type="info" @click="resetForm(ruleFormRef)"
                >取消</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog v-model="dialogLatTableVisible" :title="title" width="300">
      <div class="dialog-win">
        <el-form
          ref="ruleLatFormRef"
          :model="table"
          label-width="auto"
          :rules="latRules"
        >
          <el-form-item label="柜格名称：" prop="name">
            <el-input v-model="table.name" style="width: 240px" />
          </el-form-item>
          <el-form-item label="柜格编号：" prop="code">
            <el-input v-model="table.code" type="number" style="width: 240px" />
          </el-form-item>
          <el-form-item>
            <div class="from-but">
              <el-button type="warning" @click="submit(ruleLatFormRef)"
                >确定</el-button
              >
              <el-button type="info" @click="resetForm(ruleLatFormRef)"
                >取消</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
    <script setup>
import { CirclePlus } from "@element-plus/icons-vue";
import message from "@/util/alert.js";
import { ref, reactive, onMounted } from "vue";
import {
  getCabinetListApi,
  getCabinetLatListApi,
  updateCabinetApi,
  addCabinetApi,
  addCabinetLatApi,
  deleteCabinetLatApi,
  updateCabinetLattApi,
  startCabinetApi,
  endCabinetApi,
} from "@/api/cabinetApi.js";
import { getAllAreaListApi } from "@/api/areaApi.js";
import { useConfigStore } from "@/stores";
const configStore = useConfigStore();
// 查询参数
const query = reactive({
  areaId: "",
  queryName: "",
  pageNum: 1,
  pageSize: 10,
});
const tabelDataTotal = ref(0);
const loading = ref(false);
const tabelData = ref([]);
// 表格头部样式
const headerStyle = () => {
  return {
    backgroundColor: "#a0cfff",
    color: "#000000",
    padding: "8px 0px",
  };
};
// 表格行内样式
const tableRowClassName = ({ row }) => {
  if (row.isDeleted != "正常" && !row.code) {
    return "danger-row";
  }
  return "";
};
// 当前页改变
const currentPageChange = (num) => {
  query.pageNum = num;
  getTabelData();
};

// 获取柜子列表
const getTabelData = async () => {
  loading.value = true;
  let res = await getCabinetListApi(query);
  tabelDataTotal.value = res.data.total;
  tabelData.value = res.data.rows;
  for (let i = 0; i < tabelData.value.length; i++) {
    let res = await getCabinetLatListApi(tabelData.value[i].id);
    tabelData.value[i].children = res.data;
    tabelData.value[i].areaId = areabyIdObj.value[tabelData.value[i].areaName];
  }
  console.log(tabelData.value);
  loading.value = false;
};

// 添加图书类型
const addCabinet = () => {
  table.value = {
    areaId: "",
    name: "",
  };
  title.value = "添加图书柜";
  dialogTableVisible.value = true;
};

// 修改柜子信息
const updateCabinet = (row) => {
  table.value = JSON.parse(JSON.stringify(row));
  title.value = "修改图书柜信息";
  dialogTableVisible.value = true;
};
// 添加柜子柜格
const addCabinetLat = (id) => {
  table.value = {
    cabinetId: id,
    code: "",
    name: "",
  };
  title.value = "添加柜格";
  dialogLatTableVisible.value = true;
};
// 修改柜子柜格信息
const updateCabinetLat = (row) => {
  table.value = JSON.parse(JSON.stringify(row));
  title.value = "修改柜格信息";
  dialogLatTableVisible.value = true;
};
// 启用
const startCabinet = (id) => {
  message.confirm({
    title: "提示",
    msg: `是否启用此图书柜`,
    ok: async () => {
      await startCabinetApi(id);
      message.success(`启用成功`);
      getTabelData();
    },
  });
};
// 停用
const endCabinet = (id) => {
  message.confirm({
    title: "提示",
    msg: `是否停用此图书柜`,
    ok: async () => {
      await endCabinetApi(id);
      message.success(`停用成功`);
      getTabelData();
    },
  });
};
// 删除柜格
const deleteCabinetLat = (id) => {
  message.confirm({
    title: "提示",
    msg: `是否删除此柜格`,
    ok: async () => {
      await deleteCabinetLatApi(id);
      message.success(`删除成功`);
      getTabelData();
    },
  });
};
// 重置
const reset = () => {
  Object.assign(query, {
    areaId: "",
    queryName: "",
    pageNum: 1,
    pageSize: 10,
  });
  getTabelData();
};
// 弹窗
const table = ref({});
const dialogTableVisible = ref(false);
const dialogLatTableVisible = ref(false);
const title = ref("");
const ruleFormRef = ref(null);
const ruleLatFormRef = ref(null);
// 添加、修改的规则
const rules = reactive({
  name: [
    { required: true, message: "请输入图书柜名称", trigger: "blur" },
    { min: 2, max: 20, message: "图书柜名称长度为2-20", trigger: "blur" },
  ],
  areaId: [{ required: true, message: "请选择区域", trigger: "change" }],
  sequenceCode: [{ required: true, message: "请输入序列号", trigger: "blur" }],
  cameraId: [{ required: true, message: "请输入摄像头ID", trigger: "blur" }],
});
const latRules = reactive({
  name: [{ required: true, message: "请输入柜格名称", trigger: "blur" }],
  code: [
    { required: true, message: "请输入柜格编号", trigger: "blur" },
    { min: 1, max: 999, message: "编号为1-999", trigger: "blur" },
  ],
});
// 提交表单
const submit = async (ruleForm) => {
  if (!ruleForm) return;
  await ruleForm.validate(async (valid, fields) => {
    if (valid) {
      if (title.value == "添加图书柜") {
        await addCabinetApi(table.value);
        getTabelData();
        dialogTableVisible.value = false;
        message.success("添加图书柜成功");
      } else if (title.value == "修改图书柜信息") {
        await updateCabinetApi(table.value);
        getTabelData();
        dialogTableVisible.value = false;
        message.success("修改图书柜信息成功");
      } else if (title.value == "添加柜格") {
        await addCabinetLatApi(table.value);
        getTabelData();
        dialogLatTableVisible.value = false;
        message.success("添加柜格成功");
      } else if (title.value == "修改柜格信息") {
        await updateCabinetLattApi(table.value);
        getTabelData();
        dialogLatTableVisible.value = false;
        message.success("修改柜格信息成功");
      }
    }
  });
};
// 重置表单
const resetForm = (ruleForm) => {
  ruleForm.resetFields();
  dialogTableVisible.value = false;
  dialogLatTableVisible.value = false;
  table.value = {};
};
const areaList = ref([]);
const areabyIdObj = ref({});
onMounted(async () => {
  getTabelData();
  if (!configStore.areaList) {
    let res = await getAllAreaListApi();
    areaList.value = res.data;
    configStore.areaList = res.data;
  } else {
    areaList.value = configStore.areaList;
  }
  areaList.value.forEach((el) => {
    areabyIdObj.value[el.name] = el.id;
  });
});
</script>
    <style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  padding: 10px 20px;
  .title {
    font-size: 20px;
    font-weight: 600;
    display: flex;
    justify-content: space-between;
  }
}
.search-bar {
  margin-top: 20px;
  display: flex;
  align-items: center;
  height: 30px;
  .search-btn {
    background-color: #79bbff;
    color: #ffffff;
  }
  .el-button {
    height: 28px;
  }
}
.label-input {
  display: flex;
  color: #aaaaaa;
  height: 30px;
  align-items: center;
  margin-right: 20px;
  font-weight: 550;
  .el-input {
    border: none;
    height: 30px;
  }
}
.cut-line {
  margin-top: 30px;
  height: 1px;
  background-color: #cdd0d6;
}

.pagination {
  display: flex;
  justify-content: center;

  .el-pagination {
    margin: auto 0;
    margin-top: 10px;
  }
}
:deep(.el-table) {
  margin-top: 20px;
  .el-table__cell {
    padding: 4px;
  }
  .cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>